import Vue from 'vue'
import FormDialog from './FormDialog.vue'

function getFormDialogConstructor(options, slotCmp, confirmHandler, cancelHandler) {
  return Vue.extend({
    render(h) {
      return h(FormDialog, {
        props: {
          ...options
        },
        on: {
          'confirm' : () => {
            let slotForm = this.$refs.slotChild;
            if (slotForm && slotForm.tekeFormData) {
              let formData  = slotForm.tekeFormData();
              if (slotForm.submitForm) {
                slotForm.submitForm(formData);
              } else {
                confirmHandler(formData);
              }
            }
          },
          'cancle': () => {
            let slotForm = this.$refs.slotChild;
            if (slotForm && slotForm.clearFormData) {
              slotForm.clearFormData()
            }
          }
        },
        scopedSlots: {
          default: () => {
            return h(slotCmp, {
              ref: 'slotChild',
              props: {
                ...options
              }
            })
          }
        }
      })
    }
  })
}

function createFormDialog(options, slotCmp, confirmHandler, cancelHandler) {
  const DialogConstructor = getFormDialogConstructor(options, slotCmp, confirmHandler, cancelHandler);
  const instance = new DialogConstructor();
  instance.$mount();
  document.body.appendChild(instance.$el);
}

const formDialog = {
  show(options, slotCmp, confirmHandler, cancelHandler) {
    return createFormDialog(options, slotCmp, confirmHandler, cancelHandler)
  }
}

formDialog.install = function (Vue) {
  Vue.prototype.$formDialog = formDialog
}

export default formDialog